import 'dart:io';

import 'package:flutter/material.dart';
import 'package:pdfx/pdfx.dart';
import 'package:xim/http/apis/gfs/gfs_api.dart';
import 'package:xim/http/ase.dart';
import 'package:xim/router/index.dart';
import 'package:xim/widget/common/state.dart';

class PdfViewPage extends StatefulWidget {
  final MediaView mediaView;

  const PdfViewPage({Key? key, required this.mediaView}) : super(key: key);

  @override
  State<PdfViewPage> createState() => _PdfViewPageState();
}

class _PdfViewPageState extends State<PdfViewPage> with AppBarMixin {
  ValueNotifier<int> currPageIndex = ValueNotifier(1);
  int get totalPageIndex => pdfController?.pagesCount ?? 1;
  Future<File> get gfsFile => GfsApi.downloadGfsFile(widget.mediaView.gfsName);
  PdfController? pdfController;

  @override
  List<Widget> get appBarActions => [
        ValueListenableBuilder(
          valueListenable: currPageIndex,
          builder: (BuildContext context, int value, Widget? child) {
            return Row(
              children: [
                const Icon(Icons.chevron_left),
                Text(" ${currPageIndex.value}/$totalPageIndex "),
                const Icon(Icons.chevron_right),
                const SizedBox(
                  width: 6,
                ),
                const Icon(
                  Icons.refresh,
                ),
                const SizedBox(
                  width: 12,
                ),
              ],
            );
          },
        )
      ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBar,
      body: FutureBuilder(
        future: gfsFile,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(
              child: CircularProgressIndicator(),
            );
          } else if (snapshot.hasError) {
            return errorInfoWidget('Error: ${snapshot.error}');
          } else {
            // 加载密文数据
            var readAsBytes = snapshot.data?.readAsBytesSync();
            if (readAsBytes == null) {
              return errorInfoWidget('Error: ${snapshot.error}');
            }
            // 解密
            if (widget.mediaView.plaintextAESKey != null) {
              readAsBytes = AES.decryptAesBytes(
                  aesKey: widget.mediaView.plaintextAESKey!, encryptData: readAsBytes);
            }
            // 渲染
            pdfController =
                PdfController(document: PdfDocument.openData(readAsBytes), initialPage: 1);
            return PdfView(
                controller: pdfController!,
                scrollDirection: Axis.vertical,
                pageSnapping: false,
                onPageChanged: (pageIndex) {
                  currPageIndex.value = pageIndex;
                },
                onDocumentError: (Object error) => errorInfoWidget(error.toString()));
          }
        },
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    pdfController?.dispose();
    currPageIndex.dispose();
  }

  Widget errorInfoWidget(String errorInfo) {
    return Center(
      child: Text(errorInfo),
    );
  }

  @override
  Color get appBarBgColor => Colors.red;
}
